//
//  DestinationViewController.m
//  Qyer
//
//  Created by 赵宇 on 15/9/8.
//  Copyright (c) 2015年 赵宇. All rights reserved.
//

#import "DestinationViewController.h"
#import "BaseHeader.h"
@interface DestinationViewController ()<UITableViewDataSource, UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIGestureRecognizerDelegate>
{
    UIImageView *_mapView;
}
@end

@implementation DestinationViewController
-(void)dealloc
{
    [_inforArr release];
    [_hotcountryInforArr release];
    [_countryInforArr release];
    [_table release];
    [super dealloc];
}
-(void)viewWillAppear:(BOOL)animated
{
     self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:34./255 green:169./ 255 blue:118./255 alpha:1];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 签完UIGestureRecognizerDelegate代理,然后写这两句话,效果就是从这个页面push的其他页面都可以右滑返回上一页
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    _number = 0;// 亚洲
    
    [self creatNav];
    [self creatMapViewandButton];
    [self getTheData];
    
}

-(void)creatNav
{
    UIView *nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    nav.backgroundColor = [UIColor colorWithRed:34./255 green:169./ 255 blue:118./255 alpha:1];
    
    UIButton *search = [UIButton buttonWithType:UIButtonTypeCustom];
    search.frame = CGRectMake(50, 25, SCREEN_WIDTH-100, 30);
    search.layer.masksToBounds = YES;
    search.layer.cornerRadius = 10.;
    [search addTarget:self action:@selector(goToSearchView) forControlEvents:UIControlEventTouchUpInside];
    search.backgroundColor = [UIColor colorWithRed:27./255 green:129./255 blue:94./255 alpha:1];
    search.titleLabel.font = [UIFont systemFontOfSize:15.];
    [search setTitle:@"🔍 搜索目的地: 国家/城市" forState:UIControlStateNormal];
    [nav addSubview:search];
    [self.view addSubview:nav];
    
    [nav release];
}
-(void)goToSearchView
{
    FindViewController *findV = [[FindViewController alloc]init];
    UINavigationController *FNavC = [[UINavigationController alloc]initWithRootViewController:findV];
    
    [self presentViewController:FNavC animated:YES completion:nil];
    
    [findV release];
}

-(void)getTheData
{
    _inforArr = [[NSMutableArray alloc]init];
    _hotcountryInforArr = [[NSMutableArray alloc]init];
    _countryInforArr = [[NSMutableArray alloc]init];
    NSString *string = @"http://open.qyer.com/qyer/footprint/continent_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=25.04427337646484&lon=121.5138320922852&page=1&track_app_channel=App%2520Store&track_app_version=6.6&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=301FBCE0-A789-4EAC-ADF1-95E1AACF2A70&track_os=ios%25207.1.2&v=1";
    
  [AFNblock getdataWithUrlString:string type:_number dataBlock:^(id block) {
      
      [self dealWithDataWithDic:block];
      
  } netBlock:^(id block) {
      
      [self dealWithDataWithDic:block];
  }];
    
    
}

-(void)dealWithDataWithDic:(NSDictionary *)block
{
    NSDictionary *bigDic = block;
    _inforArr = [bigDic objectForKey:@"data"];
    NSDictionary *continentDic = [_inforArr objectAtIndex:_number];
    NSArray *hot_countryArr = [continentDic objectForKey:@"hot_country"];
    for (int j = 0; j < hot_countryArr.count; j++)
    {
        NSDictionary *hot_countryDic = [hot_countryArr objectAtIndex:j];
        hot_countryModel *hotmodel = [[hot_countryModel alloc]initWithDictionary:hot_countryDic];
        [_hotcountryInforArr addObject:hotmodel];
    }
    
    NSArray *countryArr = [continentDic objectForKey:@"country"];
    for (int k = 0; k < countryArr.count; k++) {
        NSDictionary *countryDic = [countryArr objectAtIndex:k];
        hot_countryModel *countrymodel = [[hot_countryModel alloc]initWithDictionary:countryDic];
        [_countryInforArr addObject:countrymodel];
    }
    [self creatTableview];
    [self.table reloadData];

}


-(void)creatMapViewandButton
{
    _mapView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Asian.png"]];
    _mapView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT / 3);
    [_mapView setUserInteractionEnabled:YES];
    
    UIButton *Asianbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    Asianbutton.frame = CGRectMake(_mapView.frame.size.width/7*5, _mapView.frame.size.height/6, 50, 35);
    [Asianbutton addTarget:self action:@selector(changeAsian:) forControlEvents:UIControlEventTouchUpInside];
    _number = 0;
    [_mapView addSubview:Asianbutton];
    
    UIButton *Africabutton = [UIButton buttonWithType:UIButtonTypeCustom];
    Africabutton.frame = CGRectMake(_mapView.frame.size.width/7*3+20, _mapView.frame.size.height/6*3-18, 50, 35);
    [Africabutton addTarget:self action:@selector(changeAfrica:) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:Africabutton];
    
    UIButton *Antarcticabutton = [UIButton buttonWithType:UIButtonTypeCustom];
    Antarcticabutton.frame = CGRectMake(_mapView.frame.size.width/8*5-5, _mapView.frame.size.height/6*4, 50, 35);
    [Antarcticabutton addTarget:self action:@selector(changeAntarctica:) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:Antarcticabutton];

    UIButton *Oceaniabutton = [UIButton buttonWithType:UIButtonTypeCustom];
    Oceaniabutton.frame = CGRectMake(_mapView.frame.size.width/8*6, _mapView.frame.size.height/7*3.5, 50, 35);
    [Oceaniabutton addTarget:self action:@selector(changeOceania:) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:Oceaniabutton];
    
    UIButton *SorthAmericabutton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    SorthAmericabutton.frame = CGRectMake(_mapView.frame.size.width/8*2, _mapView.frame.size.height/7*3.5, 50, 35);
    [SorthAmericabutton addTarget:self action:@selector(changeSorthAmerica:) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:SorthAmericabutton];

    UIButton *Europebutton = [UIButton buttonWithType:UIButtonTypeCustom];
    Europebutton.frame = CGRectMake(_mapView.frame.size.width/8*4, _mapView.frame.size.height/9, 50, 35);
    [Europebutton addTarget:self action:@selector(changeEurope:) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:Europebutton];

    UIButton *NorthAmericabutton = [UIButton buttonWithType:UIButtonTypeCustom];
    NorthAmericabutton.frame = CGRectMake(_mapView.frame.size.width/9, _mapView.frame.size.height/9, 50, 35);
    [NorthAmericabutton addTarget:self action:@selector(changetoNorthAmerica:) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:NorthAmericabutton];
    
}
-(void)changetoNorthAmerica:(UIButton *)sender
{
    if (sender.selected == NO) {
        [_mapView setImage:[UIImage imageNamed:@"NorthAmerica.png"]];
      
        _number = 2;
        [self getTheData];
        
    }
    else{
        sender.selected = YES;
    }
}
-(void)changeEurope:(UIButton *)sender
{
    if (sender.selected == NO) {
        [_mapView setImage:[UIImage imageNamed:@"Europe.png"]];

        _number = 1;
        [self getTheData];
    }
    else{
        sender.selected = YES;
    }
}
-(void)changeSorthAmerica:(UIButton *)sender
{
    if (sender.selected == NO) {
        [_mapView setImage:[UIImage imageNamed:@"SouthAmerica.png"]];
        _number = 3;
        [self getTheData];
    }
    else{
        sender.selected = YES;
    }
}
-(void)changeOceania:(UIButton *)sender
{
    if (sender.selected == NO) {
        [_mapView setImage:[UIImage imageNamed:@"Oceania.png"]];
        _number = 4;
        [self getTheData];
    }
    else{
        sender.selected = YES;
    }
 
}
-(void)changeAntarctica:(UIButton *)sender
{
    if (sender.selected == NO) {
        [_mapView setImage:[UIImage imageNamed:@"Antarctica.png"]];
        _number = 6;
        [self getTheData];
    }
    else{
        sender.selected = YES;
    }

}
-(void)changeAsian:(UIButton *)sender
{
    if (sender.selected == NO) {
        [_mapView setImage:[UIImage imageNamed:@"Asian.png"]];
        _number = 0;
        [self getTheData];
    }
    else{
        sender.selected = YES;
    }

}
-(void)changeAfrica:(UIButton *)sender
{
    if (sender.selected == NO) {
        [_mapView setImage:[UIImage imageNamed:@"Africa.png"]];
        _number = 5;
        [self getTheData];
    }
    else{
        sender.selected = YES;
    }
}
#pragma mark - 创建tableview
-(void)creatTableview
{
    // 先判断是否已经创建了table,如果已经有了,就刷新一下就行了,在处理数据里面刷新的 
    if (self.table == nil) {
        
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 112) style:UITableViewStylePlain];
    self.table.tableHeaderView = _mapView;
    [self.table setDataSource:self];
    [self.table setDelegate:self];
    [self.view addSubview:self.table];
    
    }
}
#pragma mark - tableview的代理方法
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
//其他洲热门城市有8个,只有南极洲有1个,Collection里一行里面放2张图,所以当热门城市有偶数个时返回的高度就应该是(_hotcountryInforArr.count/2).如果是奇数就返回(_hotcountryInforArr.count/2+1)行
        NSInteger count = 0;
        if (_hotcountryInforArr.count % 2 == 1)
        {
            count = _hotcountryInforArr.count / 2 + 1;
        }else
        {
            count = _hotcountryInforArr.count / 2;
        }
        return count *SCREEN_WIDTH / 7*4.4 + SCREEN_HEIGHT*0.12;
    }
    else
    {
        return 50;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1 + _countryInforArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// tableView里嵌套的带大图的CollectionView
    if (indexPath.row == 0) {
      static NSString *CitytableCellId = @"CitytableCell";
        CityTableViewCell *citycell = [tableView dequeueReusableCellWithIdentifier:CitytableCellId];
        if (!citycell) {
            citycell = [[CityTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CitytableCellId];
        }

        [citycell setDelegate:self];
        [citycell setDataSource:self];
        NSInteger count = 0;
// 判断热门城市数量是奇数还是偶数,如果是奇数,则_hotcountryInforArr.count/2+1,因为一行有两个chengshi,除2取整再加1
        if (_hotcountryInforArr.count % 2 == 1) {
            count = _hotcountryInforArr.count / 2 + 1;
        }else{
            count = _hotcountryInforArr.count / 2;
        }
        [citycell.collection setFrame:CGRectMake(0, 5, SCREEN_WIDTH, count*SCREEN_WIDTH/ 7*4.4 + SCREEN_HEIGHT*0.12)];
        [citycell.collection reloadData];
        
        return citycell;
    }
// 热门城市下面的普通的tableviewCell
    else{
        static NSString *normolcellId = @"normolcell";
        UITableViewCell *normalcell = [tableView dequeueReusableCellWithIdentifier:normolcellId];
        if (!normalcell) {
            normalcell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:normolcellId];
        }
        hot_countryModel *citymod = [_countryInforArr objectAtIndex:indexPath.row - 1];
        normalcell.textLabel.font = [UIFont systemFontOfSize:15.];
        
        NSString *text = [NSString stringWithFormat:@"%@  %@",citymod.cnname,citymod.enname];
        NSMutableAttributedString *multableString = [[NSMutableAttributedString alloc]initWithString:text];
        [multableString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(citymod.cnname.length , citymod.enname.length+2)];
        [multableString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.] range:NSMakeRange(citymod.cnname.length , citymod.enname.length+2)];
  
        normalcell.textLabel.attributedText = multableString;
        return normalcell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row > 0) {
        hot_countryModel *mod = [_countryInforArr objectAtIndex:indexPath.row - 1];
//"城市"跳到CountryViewController,"旅游地"跳到AllCountViewController,所以得在这块判断一下
        if ([mod.label isEqualToString:@"城市"])
        {
        CountryViewController *country = [[CountryViewController alloc]init];
        country.cid = mod.cid;
        [self.navigationController pushViewController:country animated:YES];
        }
        else{
            AllCountViewController *city = [[AllCountViewController alloc]init];
            city.urlStr = mod.cid;
            [self.navigationController pushViewController:city animated:YES];
        }
    }
}
#pragma mark - CollectionView的代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _hotcountryInforArr.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CityCollectionViewCell *collectionCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hotcity" forIndexPath:indexPath];
    hot_countryModel *hotmodel = [_hotcountryInforArr objectAtIndex:indexPath.row];

    NSURL *url = [NSURL URLWithString:hotmodel.photo];
    [collectionCell.photoView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"zhanweiPic"]];
    
    collectionCell.cnnameLabel.text = hotmodel.cnname;
    collectionCell.countLabel.text = hotmodel.count.stringValue;
    collectionCell.label.text = hotmodel.label;
    collectionCell.countLabel.numberOfLines = 0;
    collectionCell.label.numberOfLines = 0;
    CGFloat counwid = [StringWithWidth WidthWithText:collectionCell.countLabel.text height:SCREEN_HEIGHT/18 font:[UIFont systemFontOfSize:23.]];
    CGFloat labelwid =[StringWithWidth WidthWithText:collectionCell.label.text height:SCREEN_HEIGHT/18 font:[UIFont systemFontOfSize:15.]];
// count和类型都自适应了长度,让他俩等于其中一个较长的长度,比较美观
    if (counwid > labelwid) {
        labelwid = counwid;
    }else{
        counwid = labelwid;
    }
    
    collectionCell.countLabel.frame = CGRectMake(collectionCell.photoView.frame.size.width - counwid-10, 5, counwid, SCREEN_HEIGHT/18);
    
    collectionCell.label.text = hotmodel.label;
    collectionCell.label.frame = CGRectMake(collectionCell.photoView.frame.size.width - counwid-10, 5+SCREEN_HEIGHT/18, counwid, SCREEN_HEIGHT/18);
    
    
    collectionCell.ennameLabel.text = hotmodel.enname;
    return collectionCell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//"城市"跳到CountryViewController,"旅游地"跳到AllCountViewController,所以得在这块判断一下
    hot_countryModel *mod = [_hotcountryInforArr objectAtIndex:indexPath.row];
    if ([mod.label isEqualToString:@"城市"]) {
    CountryViewController *country = [[CountryViewController alloc]init];
    country.cid = mod.cid;
    [self.navigationController pushViewController:country animated:YES];
    }else{
        AllCountViewController *city = [[AllCountViewController alloc]init];
        city.urlStr = mod.cid;
        [self.navigationController pushViewController:city animated:YES];
    
    }
    
}

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    // 只有其下级页面支持右划返回
    if (self.navigationController.viewControllers.count == 1) {
        return NO;
    }else{
        return YES;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
